package org.example.demo;

import lombok.extern.slf4j.Slf4j;
import org.example.annotation.NotThreadSafe;
import org.example.annotation.ThreadSafe;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicInteger;


@Slf4j
@ThreadSafe
public class CountExample2 {

    // 请求总数
    public static int clientTotal = 5000;

    // 同时并发执行线程数
    public static int threadTotal = 50;

    // 并发安全包Atomic
    public static AtomicInteger count = new AtomicInteger();

    public static void main(String[] args) {
        ExecutorService executorService = Executors.newCachedThreadPool();
        // 同步关键类，构造方法传入的数字是多少，则同一个时刻，只运行多少个进程同时运行制定代码
        Semaphore semaphore = new Semaphore(threadTotal);
        CountDownLatch countDownLatch = new CountDownLatch(clientTotal);
        for (int i = 0; i < clientTotal; i++) {
            executorService.execute(()->{
                try {
                    //在 semaphore.acquire() 和 semaphore.release()之间的代码，同一时刻只允许制定个数的线程进入
                    semaphore.acquire();
                    add();
                    semaphore.release();
                } catch (InterruptedException e) {
                   log.error(e.getMessage(),e);
                }
                countDownLatch.countDown();
            });
        }
        try {
            countDownLatch.await();
            executorService.shutdown();
            log.info("count:{}",count);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private static void add(){
        count.incrementAndGet();
    }
}
